package com.link.base.base.wechat.controller;

import com.link.base.user.model.CoreUser;
import com.link.base.base.accnt.model.Account;
import com.link.base.base.accnt.service.AccountService;
import com.link.base.base.consumer.model.PortalAccntLineTemporary;
import com.link.base.base.consumer.service.PortalAccntLineTemporaryService;
import com.link.base.wechat.basic.ImportsFactoryStore;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.ServiceException;
import com.link.core.modules.export.ExportFactory;
import com.link.core.modules.export.ExportWriter;
import com.link.core.modules.imports.ImportReader;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 门店消费者导入导出
 *
 * @author lujiang
 */
@Controller
@RequestMapping("/link/wechat")
public class StoreAccount {
    private static final String MENU_CREATE_URL = "https://api.weixin.qq.com/cgi-bin/message/template/send"
            + "?access_token=ACCESS_TOKEN";
    @Resource
    private PortalAccntLineTemporaryService portalAccntLineTemporaryService;
    @Resource
    private AccountService accountService;

    /**
     * 导入门店消费者临时表，提交真实表详见PortalAccntLineTemporaryController exportExcelCommit
     *
     * @param entity
     * @param qps
     * @param session
     * @param request
     * @param response
     * @return
     * @throws Exception
     * @author lujiang
     */
    @RequestMapping(value = "/importData")
    @ResponseBody
    public Map<String, Object> importStoreExcelData(PortalAccntLineTemporary entity, QueryParams qps, HttpSession session,
                                                    HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>(16);

        try {
            ImportReader importReader = ImportsFactoryStore.newInstance(qps, request);
            List<PortalAccntLineTemporary> list = (List<PortalAccntLineTemporary>) importReader
                    .readList(entity.getClass());
            portalAccntLineTemporaryService.importExcelCheck(list, qps, request.getParameter("acctChannel"));
            import07ExcelData(list, qps, request);
            qps.setPageFlag(false);
            PortalAccntLineTemporary t = (PortalAccntLineTemporary) BasicModel.transformClass(entity, qps);
            t.setAccntValidate("Y");
            CoreUser landedUser = UserUtil.getUser();
            t.setCreatedBy(landedUser.getId());
            t.setAcctType("ChannelConsumer");
            t.setAcctChannel("STORE");
            t.setAccntValidate("N");
            int fail = portalAccntLineTemporaryService.queryByExamplePage(t).size();
            result.put("success", true);
            result.put("total", list.size());
            int success = portalAccntLineTemporaryService.queryByExamplePage(t).size();
            result.put("suc", success);
            result.put("fail", fail);
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 插入临时表
     *
     * @param list
     * @param qps
     * @param request
     * @throws Exception
     * @author lujiang
     * @time 2018-5-21
     */
    @Transactional(rollbackFor = ServiceException.class)
    protected void import07ExcelData(@RequestBody List<PortalAccntLineTemporary> list, QueryParams qps, HttpServletRequest request)
            throws Exception {
        for (int i = 0; list != null && i < list.size(); i++) {
            PortalAccntLineTemporary record = list.get(i);
            record.setAcctChannel("STORE");
            record.setAcctType("ChannelConsumer");
            portalAccntLineTemporaryService.insert(record);
        }
    }

    /**
     * 导出门店消费者Excel
     *
     * @author lujiang
     */

    @RequestMapping(value = "/exportStoreExcelData")
    @ResponseBody
    public Map<String, Object> exportData(Account entity, QueryParams qps, HttpSession session,
                                          HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("exportStoreExcelData")
                .withMessage("导出列表...").flush();
        Map<String, Object> result = new HashMap<String, Object>(16);
        try {
            qps.preDealSecurity(request);
            ExportWriter exportWriter = ExportFactory.newExcelInstance(qps);
            Account t = (Account) BasicModel.transformClass(entity, qps);
            while (!qps.getStopExport()) {
                List<Account> list = accountService.queryByExamplePage(t);
                if (qps.getPage() == 1) {
                    qps.setTotal(t.getTotal());
                }
                exportWriter.wirteData(list);
                t.setPage(qps.getPage());
                t.setTotalFlag(qps.getTotalFlag());
            }
            result.put("success", true);
            result.put("url", exportWriter.getUrlPath());
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

}
